#!/bin/sh

source scripts/common.sh

####################################################################################################

JPEG_VERSION=6b
JPEG_BASENAME="jpeg"

JPEG_ARCHIVE="${JPEG_BASENAME}src.v${JPEG_VERSION}.tar.gz"
JPEG_URL="http://www.hdfgroup.org/ftp/lib-external/jpeg/src/${JPEG_ARCHIVE}"

JPEG_PATCH_ARCHIVE="jpegpatch.zip"
JPEG_PATCH_URL="http://www.kyngchaos.com/files/macosxport/patches/${JPEG_PATCH_ARCHIVE}"

JPEG_LIBTOOL_ARCHIVE="libtool135update.zip"
JPEG_LIBTOOL_URL="http://www.kyngchaos.com/files/macosxport/patches/${JPEG_LIBTOOL_ARCHIVE}"

JPEG_DIR="${JPEG_BASENAME}-${JPEG_VERSION}"
JPEG_PREFIX="${THIRD_PARTY_PREFIX}/${JPEG_BASENAME}"
JPEG_LIB=libjpeg.a

####################################################################################################

function build_jpeg()
{

target=$1

mkdir -p ${THIRD_PARTY_BUILD} || exit 1
pushd ${THIRD_PARTY_BUILD} || exit 1

report ""
report "Removing old build from '${JPEG_DIR}'..."
rm -fr $JPEG_DIR
rm -fr $JPEG_PREFIX/${target}

report "Preparing ${target} '${JPEG_BASENAME}'..."

fetch $JPEG_URL $JPEG_ARCHIVE


pushd ${JPEG_DIR} || exit 1
mkdir -p ${target} || exit 1

report "Patching ${target} '${JPEG_BASENAME}'..."
report ""

fetch $JPEG_PATCH_URL $JPEG_PATCH_ARCHIVE
fetch $JPEG_LIBTOOL_URL $JPEG_LIBTOOL_ARCHIVE

cp -f /usr/share/libtool/config/config.sub . || exit -1
cp -f /usr/share/libtool/config/config.guess . || exit -1

patch makefile.cfg makefile.cfg.patch || exit -1

report "Configuring ${target} '${JPEG_BASENAME}'..."
report ""

./configure \
		CXXFLAGS="${SYSROOT} -arch ${target}" \
		CFLAGS="${SYSROOT} -arch ${target}" \
		LDFLAGS="-Wl,-syslibroot,${DEVSDK} -arch ${target}" \
		--prefix=${JPEG_PREFIX}/${target} \
        --host=${target}-apple-darwin \
        --target=${target}-apple-darwin \
        --disable-shared \
        --enable-static \
        --disable-dependency-tracking

if test $? -ne 0; then
        echo "configure failed"
        exit 1
fi

report "Building ${target} '${JPEG_BASENAME}'..."
nice make -j4 || exit 1
nice make install || exit 1
nice make install-lib || exit 1
nice make install-headers || exit 1

report "Built ${target} '${JPEG_BASENAME}'"
report ""

popd
popd

}

####################################################################################################

build_for_snow_leopard
for target in 'i686' 'x86_64' 'ppc'
do
	build_jpeg $target
done

create_universal_lib ${JPEG_PREFIX} ${JPEG_LIB}
create_intel_lib ${JPEG_PREFIX} ${JPEG_LIB}
create_powerpc_lib ${JPEG_PREFIX} ${JPEG_LIB}

####################################################################################################

